var ManageWindow = {
  uninstallList: [],
  scriptsLocator: TailsNS.ScriptManager.getScriptLocator(),

  init: function() {
    this.scriptsLocator.load();
    this._loadControls();
    if (this.scriptsLocator.scripts.length != 0) {
      this._populateChooser();
      this._chooseScript(0);
    }
  },

  handleOkButton: function() {
    for (var i = 0, script = null; (script = this.uninstallList[i]); i++) {
      var idx = this.scriptsLocator.find(script.namespace, script.name);
        this.scriptsLocator.scripts.splice(idx, 1);
    }
    this.scriptsLocator.save();

    for (var i = 0, script = null; (script = this.uninstallList[i]); i++) {
      TailsNS.ScriptManager.getScriptFile(script.filename).remove(false);
    }
    return true;
  },
  _populateChooser: function() {
    for (var i = 0, script = null; (script = this.scriptsLocator.scripts[i]); i++) {
      var listitem = document.createElement("listitem");

      listitem.setAttribute("label", script.name);
      listitem.setAttribute("crop", "end");
      listitem.script = script;
      if (!script.enabled) {
        listitem.style.color = 'gray';
      }
      this.listbox.appendChild(listitem);
    }
  },
  _chooseScript: function(index) {
    this.listbox.selectedIndex = index;            
    this.listbox.focus();
  },
  _loadControls: function() {
    this.listbox = document.getElementById("lstScripts");
    this.header = document.getElementById("ctlHeader");
    this.description = document.getElementById("ctlDescription");
    this.btnUninstall = document.getElementById("btnUninstall");
    this.pagesControl = new PagesControl(document.getElementById("pages-control"));
    this.chkEnabled = document.getElementById("chkEnabled");

    Tails_listen(this.listbox, "select", Tails_hitch(this, "_updateDetails"));
    Tails_listen(this.btnUninstall, "command", Tails_hitch(this, "_handleUninstallButton"));
    Tails_listen(this.chkEnabled, "command", Tails_hitch(this, "_handleEnabledCheckbox"));
  },
  _updateDetails: function() {
    if (this.listbox.selectedCount == 0) {
      this.selectedScript = null;
      this.header.textContent = " ";
      this.description.textContent = " ";
      this.chkEnabled.checked = true;
      this.pagesControl.clear();
      document.documentElement.getButton("accept").disabled = false;
    } else {
      this.selectedScript = this.listbox.getSelectedItem(0).script;
      this.header.textContent = this.selectedScript.name;
      this.description.textContent = this.selectedScript.description;
      this.chkEnabled.checked = this.selectedScript.enabled;
      this.pagesControl.populate(this.selectedScript);
    }
  },
  _handleUninstallButton: function() {
    this.uninstallList.push(this.selectedScript);
    this.listbox.removeChild(this.listbox.childNodes[this.listbox.selectedIndex]);
    if (this.listbox.childNodes.length > 0) {
      this._chooseScript(Math.max(Math.min(this.listbox.selectedIndex, this.listbox.childNodes.length - 1), 0));
    }
  },
  _handleEnabledCheckbox: function() {
    if (this.selectedScript) {
      this.selectedScript.enabled = this.chkEnabled.checked;
      if (this.selectedScript.enabled) {
        this.listbox.selectedItem.style.color = '';
      } else {
        this.listbox.selectedItem.style.color = 'gray';
      }
    }
  }
};
window.addEventListener("load", function(ev) {ManageWindow.init();}, false);

function PagesControl(ctlPages) {
  var includesBox = new PagesBox(document.getElementById("grpIncluded"));

  this.populate = function(script) {
    includesBox.populate(script.includes);
  }

  this.clear = function() {
    includesBox.clear();
  }

  function PagesBox(grpBox) {
    var buttons = grpBox.getElementsByTagName("button");
    var self = this;
    var selectedPage = null;

    this.pages = null;
    this.groupbox = grpBox;
    this.listbox = grpBox.getElementsByTagName("listbox")[0];
    this.btnAdd = buttons[0];
    this.btnRemove = buttons[1];

    this.listbox.addEventListener("select", updatePagesBox, true);
    this.btnAdd.addEventListener("command", promptForNewPage, true);
    this.btnRemove.addEventListener("command", remove, true);

    this.populate = function(pages) {
      this.clear();
      this.pages = pages;

      for (var i = 0, page = null; (page = self.pages[i]); i++) {
        addPage(page);
      }
      self.btnAdd.disabled = false;
    }

    this.clear = function() {
      this.pages = null;

      while (this.listbox.hasChildNodes()) {
        this.listbox.removeChild(this.listbox.childNodes[0]);
      }
      this.btnAdd = buttons[0];
      this.btnRemove = buttons[1];
      this.btnAdd.disabled = true;
      this.btnRemove.disabled = true;
    }

    function updatePagesBox(ev) {
      selectedPage = self.listbox.getSelectedItem(0);
      self.btnRemove.disabled = selectedPage == null;
    }

    function promptForNewPage(ev) {
      var val = prompt(TailsNS.getMessage("manage.add_object_type_prompt_message"), "hcard",
          TailsNS.getMessage("manage.add_object_type_prompt_title"));
      if (val && val != "") {
        addPage(val);
        self.pages.push(val);
        dirty = true;
      }
    }

    function prompt(msg, defVal, title) {
      var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
          .getService(Components.interfaces.nsIPromptService);
      var result = {value:defVal};

      if (promptService.prompt(null, title, msg, result, null, {value:0})) {
        return result.value;
      } else {
        return null;
      }
    }

    function remove(ev) {
      self.pages.splice(self.listbox.selectedIndex, 1);
      self.listbox.removeChild(self.listbox.getSelectedItem(0));

      // it's sorta wierd that the button stays focused when it is disabled because nothing is selected
      if (self.listbox.length == 0) {
        self.listbox.focus();
        dirty = true;
      }
    }

    function addPage(pageSpec) {
      var listitem = document.createElement("listitem");
      listitem.setAttribute("label", pageSpec);
      self.listbox.appendChild(listitem);
    }
  }
}

